package com.mall.interceptor;

import com.alibaba.fastjson.JSON;
import com.mall.entity.User;
import com.mall.utils.UserCache;
import com.mall.vo.WebResult;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
 /*   @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        //查看是否有token,没有则不放行
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            response.getWriter().write(JSON.toJSONString(WebResult.builder().code(307).message("未登录").build()));
            return false;
        }
        //有token就去redis里验证
        try {
            String s = stringRedisTemplate.opsForValue().get(token);
            User user = JSON.parseObject(s,User.class);
            if (user==null){
                response.getWriter().write(JSON.toJSONString(WebResult.builder().code(308).message("登录过期，请重新登录").build()));
                return false;
            }
            UserCache.put(user);
        }catch (Exception e){
            e.printStackTrace();
            response.getWriter().write(JSON.toJSONString(WebResult.builder().code(309).message("发生异常").build()));
        }
        String ntoken = UUID.randomUUID().toString().replace("-", "");
        //把key值替换
        stringRedisTemplate.rename(token,ntoken);
        //重置过期时间
        stringRedisTemplate.expire(ntoken,7, TimeUnit.DAYS);
        //更新给前端的令牌
        response.setHeader("token",ntoken);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserCache.remove();
//        //获取旧令牌
//        String otoken = request.getHeader("token");
//        //得到新令牌
//        String ntoken = UUID.randomUUID().toString().replace("-", "");
//        //把key值替换
//        stringRedisTemplate.rename(otoken,ntoken);
//        //重置过期时间
//        stringRedisTemplate.expire(ntoken,7, TimeUnit.DAYS);
//        //更新给前端的令牌
//        response.setHeader("token",ntoken);
    }*/
}
